package com.ruoyi.transaction.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;

import com.ruoyi.common.entity.TransactionEntity.ShopOrder;
import com.ruoyi.transaction.service.IShopOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;


@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private IShopOrderService iShopOrderService;

    /**
     * 生成支付二维码
     */
    @GetMapping("/pay")
    public JSONObject pay(@RequestParam String outTradeNo) {
        JSONObject result = new JSONObject();

        // 查询订单
        ShopOrder queryOrder = new ShopOrder();
        queryOrder.setOrderNo(outTradeNo);
        List<ShopOrder> orderList = iShopOrderService.selectShopOrderList(queryOrder);
        if (orderList == null || orderList.isEmpty()) {
            result.put("code", 500);
            result.put("msg", "订单不存在：" + outTradeNo);
            return result;
        }

        BigDecimal amount = orderList.get(0).getTotalAmount();
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            result.put("code", 500);
            result.put("msg", "订单金额异常：" + outTradeNo);
            return result;
        }

        // 调用支付宝接口
        Factory.setOptions(getAlipayConfig());
        AlipayTradePrecreateResponse response;
        try {
            response = Factory.Payment.FaceToFace()
                    .preCreate("订单支付：" + outTradeNo, outTradeNo, amount.toPlainString());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "调用支付宝失败：" + e.getMessage());
            return result;
        }

        JSONObject jsonObject = JSONUtil.parseObj(response.getHttpBody());
        JSONObject precreateResponse = jsonObject.getJSONObject("alipay_trade_precreate_response");

        if (precreateResponse == null || precreateResponse.getStr("qr_code") == null) {
            result.put("code", 500);
            result.put("msg", "二维码生成失败，支付宝返回：" + response.getHttpBody());
            return result;
        }

        String qrContent = precreateResponse.getStr("qr_code");

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            // 生成二维码到字节流
            QrCodeUtil.generate(qrContent, 300, 300, "png", out);
            // 转成 Base64
            String qrCodeBase64 = cn.hutool.core.codec.Base64.encode(out.toByteArray());
            result.put("qrCodeBase64", qrCodeBase64);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "二维码生成异常：" + e.getMessage());
            return result;
        }

        result.put("code", 200);
        result.put("msg", "成功");
        result.put("outTradeNo", outTradeNo);
        return result;
    }
    /**
     * 支付宝异步回调
     */
    @PostMapping("/notify")
    public String notifyUrl(HttpServletRequest request) {
        System.out.println("收到支付宝回调...");

        String outTradeNo = request.getParameter("out_trade_no");
        String tradeStatus = request.getParameter("trade_status");

        System.out.println("订单号：" + outTradeNo);
        System.out.println("交易状态：" + tradeStatus);

        // TODO: 验签 + 订单状态更新（幂等处理）

        return "success";
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/queryPay")
    public JSONObject queryPay(@RequestParam String outTradeNo) throws Exception {
        Factory.setOptions(getAlipayConfig());
        AlipayTradeQueryResponse queryResponse = Factory.Payment.Common().query(outTradeNo);
        String httpBody = queryResponse.getHttpBody();
        System.out.println("查询结果：" + httpBody);

        JSONObject jsonObject = JSONUtil.parseObj(httpBody);
        return jsonObject.getJSONObject("alipay_trade_query_response"); // 返回完整对象
    }

    /**
     * 支付宝SDK配置
     */
    private Config getAlipayConfig() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi-sandbox.dl.alipaydev.com"; // 沙箱网关
        config.merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCUDSUtonPj6hfA64DT+BvF0TJ4Y6rYynhGoUnJduQU4+IMrpEijpk2zgh0GpLixplZ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riJYiNEfMMzAfZG46IL98rqDwNdOY7AQkKhy+a9zgH/aX6+Qo+alGm1CLo6S9jcyW0DSlV8Fqir1IQuAAQKBgFvuL+fm+WOpzlIwwvgekRnPE9apCIbjGlBcy7UYEAl1enoOx7pXD4AR3z4lO/STRlVc0mNrB4oXUUamD8qByEHwOw8U5/avsuM1WBlilNi56Sgl7Kk/8xHgB9OzdpMAMlk+uuDpUBX0m1t0rCn2Hwalav2Eto9p58k1ymfE/rxpAoGBALrQVy1zSXI42zC9qKCBfEvKZ9066Mybx2jzAxfMUL9fv25KLVbgyQaXCtOCiJP2AujHRXwF8wbA5wg9weyIZCILhpH3iuinXTel4ZDm8EoEg8cb8De1zNb7hwipDW49j1qTzKKKmFSYB99KzAi1pjrlnvzsvVkKgAzLoFsn7NGp";
        config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj+JxV9BTmozGriWFypef01rpPLRla/avnfEc28PlnxqKGn8nLctNhj4QrMlCCzFkPXh+Y359e8z9l2KqWv53y40WYAOYNY+6f3S+AXvsXDabOSzkZoyRd2wmO91m2imwlWamEYciyX40hwejZ4P0fnPdf4g18bhfLB8dqjhXeKK8q+SPngSKJsO1r2GAFPc2wfCXyIIC07jjEpfBJbDm1QbNHWto/QpyfALSh+ohSapMpUvBYtJ2nSO6CkqcL+mS3Fqxj3MDkqZTOJazP35S0wBUG4MP4Xh7/6m+liWOu2GKLhsg7FpAe8ViW6WdGldn2XZV36H6qB+2g4zIDoSCcwIDAQAB";
        config.signType = "RSA2";
        config.appId = "9021000151617815";
        config.notifyUrl = "http://zd69444a.natappfree.cc/alipay/notify"; // 内网穿透地址
        return config;
    }
}
